import { Breadcrumb, Button, Form, Steps, Input, Result, Space, message } from "antd";
import styled from "styled-components";
import { Link } from "react-router-dom";
import { useThemeToken } from "@/theme/hooks";
import { useState, forwardRef, useImperativeHandle, useRef, useEffect } from "react";
import InputForm from "./modules/design/InputForm";
import StructureForm from "./modules/design/StructureForm";
import ResponseView from "./modules/design/ResponseView";
import { useParams, useRouter } from "@/router/hooks";
import { CircleLoading } from '@/components/loading';
import { dataSubjectDetail, dataSubjectDesign } from '@/api/sharing/dataSubject'

import PublishModalForm from "./modules/PublishModalForm";

const steps = [
  {
    title: '输入设计',
  },
  {
    title: '结构设计',
  },
  {
    title: '响应预览',
  },
  {
    title: '创建完成',
    disabled: true,
  },
];


const DataSubjectDesign = () => {
  const [current, setCurrent] = useState(0);
  const formRefs = useRef([])
  const routeParams = useParams()
  const [loading, setLoading] = useState(true)
  const [subjectDetail, setSubjectDetail] = useState({})
  const router = useRouter()
  const [submitLoading, setSubmitLoading] = useState(false)
  const next = () => {

    setCurrent(current + 1);
  };
  const prev = () => {
    setCurrent(current - 1);
  };

  const handleDone = () => {
    if (current === 1) {
      setSubmitLoading(true)
      formRefs.current[1].validateFields().then(() => {
        return formRefs.current[1].submit().then(res => {
          if (res.code === 200) {
            message.success('保存成功！')
          }
        })
      }).catch((e) => {
        console.log(e)
      }).finally(() => {
        setSubmitLoading(false)
      })
    } else if (current === 2) {
      formRefs.current[0].validateFields().then((values) => {
        return dataSubjectDesign({
          id: routeParams.id,
          themeParamDtos: values.paramList,
          previewResult: formRefs.current[2].value,
        }).then(res => {
          if (res.code === 200) {
            message.success('保存成功')
            setCurrent(current + 1)
          }
        })
      }).catch(e => {
        console.log(e)
        setCurrent(0)
      }).finally(() => {
        setSubmitLoading(false)
      })
    }
  }

  const publishOnFinish = () => {
    message.success('发布成功')
    router.push('/integration/sharing/dataSubject')
  };

  useEffect(() => {
    if (routeParams.id) {
      dataSubjectDetail({ id: routeParams.id }).then((res) => {
        setSubjectDetail(res?.result || {})
        if (res.code === 200) {
          setLoading(false)
        }
      })
    } else {
      message.error('未找到主题')
    }
  }, [])

  if (loading) {
    return <CircleLoading />
  }

  return (<StyleWrap>
    <div className="page-breadcrumb">
      <Breadcrumb
        items={[
          {
            title: <Link to="/integration/sharing/dataSubject">主题管理</Link>,
          },
          {
            title: '主题设计',
          }
        ]}
      />
    </div>
    <div className="steps-wrapper"><Steps current={current} items={steps} onChange={setCurrent} /></div>

    <div className="forms-wrapper">
      <InputForm style={{ display: current === 0 ? 'block' : 'none' }} ref={(el) => { if (el) formRefs.current[0] = el }} subjectDetail={subjectDetail} />
      <StructureForm style={{ display: current === 1 ? 'flex' : 'none' }} ref={(el) => { if (el) formRefs.current[1] = el }} subjectDetail={subjectDetail} />
      {
        current === 2 && <ResponseView ref={(el) => { if (el) formRefs.current[2] = el }} subjectDetail={subjectDetail} />
      }

      <Result
        style={{ display: current === 3 ? 'block' : 'none' }}
        status="success"
        title="主题设计完成!"
        extra={[
          <Link key="console" to={`/integration/sharing/dataSubject`}>
            <Button type="primary" >
              返回主题管理
            </Button>
          </Link>,
          <PublishModalForm key="buy" trigger={<Button>立即发布</Button>} onFinish={publishOnFinish} initialValues={{
            ...subjectDetail
          }} />
        ]}
      />
    </div>

    <div className="buttons-wrapper">
      <Space
        size="large"
        style={{
          marginTop: 24,
          display: current === steps.length - 1 ? 'none' : undefined,
        }}
      >
        <Button disabled={current === 0 || current === steps.length - 1} onClick={() => prev()}>上一步</Button>
        <Button disabled={current >= steps.length - 2} onClick={() => next()}>下一步</Button>
        {current === 1 && <Button type="primary" onClick={handleDone} loading={submitLoading}>保存</Button>}
        {current === 2 && <Button type="primary" onClick={handleDone} loading={submitLoading}>完成并提交</Button>}
      </Space>


    </div>

  </StyleWrap>);
}

const StyleWrap = styled.div`
  padding: 16px;
  .steps-wrapper{
    width: 70%;
    margin: 0 auto;
  }
  .forms-wrapper{
    margin-top: 30px;
  }
  .buttons-wrapper{
    /* width: 70%; */
    text-align: center;
    margin-top: 20px;
  }

  .ant-input, textarea.ant-input,.ant-select{
    max-width: 600px;
  }
  .ant-form-item-label{
    width: 120px;
    text-align: right;
  }
`
export default DataSubjectDesign;